package com.cdhong.shop.backend.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author CDHong
 * @Date Created in 2024/4/20 9:15
 * @Version 1.0
 */
public class JWTUtil {

    // 密钥
    private static final String SIGNATURE = "!Q@W#E$R";

    /**
     * @Description 传入payload信息生成Token，默认3天过期
     * @Author CDHong
     * @Param [map]  payload信息
     * @Date 2024/4/20 9:17
     **/
    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        // payload
        map.forEach(builder::withClaim);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 3); //默认3天过期
        // 设置过期时间
        builder.withExpiresAt(instance.getTime());
        // 基于payload和密钥使用HMAC256算法进行加密生成Token
        return builder.sign(Algorithm.HMAC256(SIGNATURE));
    }

    /**
     * @Description 校验Token是否合法
     * @Author CDHong
     * @Param [token]
     * @Date 2024/4/20 9:20
     **/
    public static DecodedJWT verify(String token) {
        /*
         *  如果有任何验证异常，此处都会抛出异常
         *  SignatureVerificationException 签名不一致异常
         *  TokenExpiredException 令牌过期异常
         *  AlgorithmMismatchException 算法不匹配异常
         *  InvalidClaimException 失效的payload异常
         **/
        DecodedJWT verify = null;
        try {
            verify = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        } catch (Exception e) {
            System.out.println("Token验证异常：" + e.getMessage());
        }
        return verify;
    }


    public static void main(String[] args) {
        Map<String, String> payload = new HashMap<>();
        payload.put("username", "admin");
        String pwd = DigestUtils.md5Hex("123456" + SaltMD5Util.createSlat(16));
        System.out.println("pwd: " + pwd);
        payload.put("password", pwd);
        // 生成Token
        String token = JWTUtil.getToken(payload);
        System.out.println("Token：" + token);
        // 验证Token
        // String myToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6ImE3YzM2OWUyZjkwZjIyYjg2MDVkNjZlODVlMzVkNDNmIiwiZXhwIjoxNzEzODM1NTAxLCJ1c2VybmFtZSI6ImFkbWluIn0.m0i0nmdVug3r3bri7wqqb-KfgIfA49EnvkTAxWSbkIc";
        DecodedJWT decodedJWT = JWTUtil.verify(token);
        System.out.println(decodedJWT);
        // 获取Token信息
        System.out.println("username：" + decodedJWT.getClaim("username").asString());
        System.out.println("password：" + decodedJWT.getClaim("password").asString());
        System.out.println("过期时间：" + decodedJWT.getExpiresAt());


    }

}
